# 1 导入库及设置GPU
# 1.1 导入库
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms, datasets
import copy
from PIL import Image
from datetime import datetime
import matplotlib.pyplot as plt
import warnings

warnings.filterwarnings("ignore")               #忽略警告信息
plt.rcParams['font.sans-serif']    = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False      # 用来正常显示负号
plt.rcParams['figure.dpi']         = 100        #分辨率

# 1.2 设置GPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 2 数据处理
# 2.1 数据下载
data_dir = '/Users/sunhaoqing/Desktop/pythonProject/深度学习/2 Pytorch入门/data/马铃薯病害识别'

# 2.2 数据预处理
data_transforms = transforms.Compose([
    transforms.Resize([224, 224]),
    transforms.ToTensor(),
    transforms.Normalize(
        mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225]
    )
])

total_data = datasets.ImageFolder(data_dir, transform=data_transforms)

# 2.3 划分数据集
train_size = int(0.8 * len(total_data))
test_size = len(total_data) - train_size

train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size,test_size])

# 2.4 数据加载
batch_size = 32

train_dl = torch.utils.data.DataLoader(
    train_dataset,
    batch_size=batch_size,
    shuffle=True,
    num_workers=0
)

test_dl = torch.utils.data.DataLoader(
    test_dataset,
    batch_size=batch_size,
    num_workers=0
)

# 3 构建VGG-16模型
class vgg16(nn.Module):
    def __init__(self):
        super(vgg16, self).__init__()
        # 卷积块1
        self.block1 = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=1),
            nn.ReLU(),
            nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2,stride=2)
        )
        # 卷积块2
        self.block2 = nn.Sequential(
            nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1),
            nn.ReLU(),
            nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2)
        )
        # 卷积块3
        self.block3 = nn.Sequential(
            nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1),
            nn.ReLU(),
            nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2)
        )
        # 卷积块4
        self.block4 = nn.Sequential(
            nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1),
            nn.ReLU(),
            nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2)
        )
        # 卷积块5
        self.block5 = nn.Sequential(
            nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
            nn.ReLU(),
            nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2)
        )
        # 全连接层(用于分类)
        self.classifier = nn.Sequential(
            nn.Linear(in_features=512*7*7, out_features=4096),
            nn.ReLU(),
            nn.Linear(in_features=4096, out_features=4096),
            nn.ReLU(),
            nn.Linear(in_features=4096, out_features=3)
        )

    def forward(self, x):
        x = self.block1(x)
        x = self.block2(x)
        x = self.block3(x)
        x = self.block4(x)
        x = self.block5(x)
        x = torch.flatten(x, start_dim=1)
        x = self.classifier(x)

        return x

# 4 模型训练
# 4.1 设置超参数
model = vgg16().to(device)
loss_fn    = nn.CrossEntropyLoss()
optimizer  = torch.optim.Adam(model.parameters(), lr= 1e-4)

# 4.2 训练函数
def train(dataloader, model, loss_fn, optimizer):
    # 初始化
    size = len(dataloader.dataset)   # 训练集大小
    num_batches = len(dataloader)    # 批次数目

    train_loss = 0   # 初始化训练损失
    train_acc = 0    # 初始化训练正确率

    # 获取图片及标签
    for X,y in dataloader:
        X = X.to(device)
        y = y.to(device)

        # 计算测试误差
        pred = model(X)
        loss = loss_fn(pred, y)

        # 反向传播
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        # 记录总acc和loss
        train_acc += (pred.argmax(1)==y).type(torch.float).sum().item()
        train_loss += loss.item()

    # 计算acc和loss结果
    train_acc /= size
    train_loss /= num_batches

    return train_acc, train_loss

# 4.3 测试函数
def test(dataloader, model, loss_fn):
    # 初始化
    size = len(dataloader.dataset)   # 测试集大小
    num_batches = len(dataloader)    # 批次数目

    test_loss = 0   # 初始化测试损失
    test_acc = 0    # 初始化测试正确率

    # 不进行训练暂停梯度更新
    with torch.no_grad():

        # 获取图片及标签
        for imgs,target in dataloader:
            imgs = imgs.to(device)
            target = target.to(device)

            # 计算测试误差
            target_pred = model(imgs)
            loss = loss_fn(target_pred, target)

            # 记录总acc和loss
            test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()
            test_loss += loss.item()

    # 计算acc和loss结果
    test_acc /= size
    test_loss /= num_batches

    return test_acc, test_loss

# 5 正式训练
# 5.1 初始化
epochs = 40
train_loss = []
train_acc  = []
test_loss  = []
test_acc   = []
best_acc = 0

# 5.2 轮次迭代
for epoch in range(epochs):

    # 模型训练
    model.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)

    # 模型评估
    epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)

    # 保存最佳模型到 best_model
    if epoch_test_acc > best_acc:
        best_acc = epoch_test_acc
        best_model = copy.deepcopy(model)

    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)

    # 获取当前学习率
    lr = optimizer.param_groups[0]['lr']

    template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f}, Lr:{:.2E}')
    print(template.format(epoch + 1, epoch_train_acc * 100, epoch_train_loss,
                          epoch_test_acc * 100, epoch_test_loss, lr))

# 5.3 保存最佳模型到文件中
PATH = './best_model.pth'  # 保存的参数文件名
torch.save(best_model.state_dict(), PATH)

# 6 结果可视化
current_time = datetime.now() # 获取当前时间

epochs_range = range(epochs)

plt.figure(figsize=(12, 3))

plt.subplot(1, 2, 1)
plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.xlabel('Epoch')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.xlabel('Epoch')

plt.suptitle(f"Run at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

plt.show()

# 7 评估图片
def predict_one_image(image_path, model, transform, classes):
    # 读取图片
    test_img = Image.open(image_path).convert('RGB')
    plt.imshow(test_img)
    plt.axis('off')
    plt.show()

    # 预处理
    test_img = transform(test_img)
    img = test_img.unsqueeze(0).to(device)  # [1,3,224,224]

    # 推理
    model.eval()
    with torch.no_grad():
        output = model(img)
        _, pred = torch.max(output, 1)
        pred_class = classes[pred.item()]

    # 输出结果
    print(f"预测结果是：{pred_class}")